{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "_llm = ChatOpenAI(\n",
    "    api_key=\"ollama\",\n",
    "    model=\"qwen2.5:7b\",\n",
    "    base_url=\"http://192.168.10.11:60026/v1\",\n",
    "    temperature=0.7,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='好的，我已经记住了，您叫张三。有什么我可以帮助您的吗？', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 18, 'prompt_tokens': 36, 'total_tokens': 54, 'completion_tokens_details': None}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-16505fc4-4387-44eb-bdd2-bccf4f2613c7-0', usage_metadata={'input_tokens': 36, 'output_tokens': 18, 'total_tokens': 54, 'input_token_details': {}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "_llm.invoke(\"请记住我叫张三！\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='你是来自外部的用户，正在与阿里云开发的大型语言模型Qwen进行对话。你可以告诉我更多关于你自己的信息，让我们之间的对话更加有趣和有意义哦！', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 38, 'prompt_tokens': 32, 'total_tokens': 70, 'completion_tokens_details': None}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-189b5a51-da8e-4fe0-8ce7-6eb4dc2cfe88-0', usage_metadata={'input_tokens': 32, 'output_tokens': 38, 'total_tokens': 70, 'input_token_details': {}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "_llm.invoke(\"我是谁?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='您是张三。如果您有任何问题或需要帮助，请告诉我！', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 65, 'total_tokens': 80, 'completion_tokens_details': None}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-0c9c1688-5e26-4bda-928a-4a90d6c9f1a2-0', usage_metadata={'input_tokens': 65, 'output_tokens': 15, 'total_tokens': 80, 'input_token_details': {}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "store = [HumanMessage(\"请记住我叫张三！\")]\n",
    "\n",
    "rep = _llm.invoke(store)\n",
    "store.append(rep)\n",
    "store.append(HumanMessage(\"我是谁\"))\n",
    "rep = _llm.invoke(store)\n",
    "rep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_message_histories import ChatMessageHistory\n",
    "\n",
    "_store = {}\n",
    "\n",
    "\n",
    "def get_session_history(session_id):\n",
    "    if session_id not in _store:\n",
    "        _store[session_id] = ChatMessageHistory()\n",
    "    return _store[session_id]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "\n",
    "_messages = ChatPromptTemplate(\n",
    "    [\n",
    "        (\"system\", \"请用中文帮助用户\"),\n",
    "        MessagesPlaceholder(variable_name=\"history_contents\"),\n",
    "        (\"human\", \"{content}\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.output_parsers import StrOutputParser\n",
    "\n",
    "_chain = _messages | _llm | StrOutputParser()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "好的，您已成功备注为“张三”。如需在后续的对话中继续使用这一称呼，请直接称呼您为“张三”，我会这样称呼您。如果您有其他问题或需要帮忙的事，尽管告诉我！\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.runnables import RunnableWithMessageHistory\n",
    "\n",
    "_his_chain = RunnableWithMessageHistory(\n",
    "    _chain,\n",
    "    get_session_history,\n",
    "    input_messages_key=\"content\",\n",
    "    history_messages_key=\"history_contents\",\n",
    ")\n",
    "\n",
    "rep01 = _his_chain.invoke(\n",
    "    {\"content\": \"记住我叫张三\"}, config={\"configurable\": {\"session_id\": \"1\"}}\n",
    ")\n",
    "print(rep01)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您刚才说您叫张三。所以您的名字是张三。如果您有其他名字或需要确认其他信息，请告诉我！\n"
     ]
    }
   ],
   "source": [
    "rep02 = _his_chain.invoke(\n",
    "    {\"content\": \"我叫什么名字\"}, config={\"configurable\": {\"session_id\": \"1\"}}\n",
    ")\n",
    "print(rep02)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您在对话中并没有提到您的姓名，所以我无法直接得知您的名字。如果您告诉我或者在后续的问题中提到您的名字，我很乐意知道。\n"
     ]
    }
   ],
   "source": [
    "rep03 = _his_chain.invoke(\n",
    "    {\"content\": \"我叫什么名字\"}, config={\"configurable\": {\"session_id\": \"2\"}}\n",
    ")\n",
    "print(rep03)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python310",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
